//
//  CameraEffectViewController.m
//  OpenGLGame
//
//  Created by Nguyen Cong Huy on 11/23/12.
//  Copyright (c) 2012 UIT. All rights reserved.
//

#import "CameraEffectViewController.h"
#import "Utils.h"
#import "EAGLCameraView.h"
#include "LBTexture.h"
#import "OCImage.h"
#import "CropViewController.h"

#define scrollBarWidth 320
#define scrollBarHeight 60
#define buttonWidth 80
#define buttonHeight scrollBarHeight
#define border 2
#define numButton 10

#define NUM_BUTTON_IMAGE 4
#define W_BUTTON_IMAGE 40
#define H_BUTTON_IMAGE 40
#define DISTANCE_BUTTON_IMAGE 10
#define FROM_BOTTOM_TO_GL_VIEW 60
#define STANDARD_BRIGHTNESS 0.1

#define W_BUTTON_MENU_BAR 48
#define H_BUTTON_MENU_BAR 40

#define CAPTURE_INDEX 0

@interface CameraEffectViewController() {
    
@private
    ImageMainMenuBarView* actionBarEffectNew;
    EAGLCameraView* eaglView;
    ImageActionBarView* actionBarMenu;
    ImageActionBarView* actionBarCapture;
    int actionBarUsing;
    UIView* loadingView;
    UIView* changeSmoothValueView;
    UISlider* smoothSlider;
    UISlider* brightnessSlider;
    UISlider* sharpenSlider;
    UIButton* flashButton;
    UIButton* switchCameraButton;
    UIButton* effectButton;
    
    bool isEnableChangeSmoothValue;
    
    UIImage* activeSkinIcon, *inactiveSkinIcon;
    UIImage* activeBackgroundImage;
    
    bool isProcessDefaultValue;             // when input image, slider will set default value. So,
    
    int effectButtonIndex;
    int rotateButtonIndex;
    int cropButtonIndex;
    int smoothSkinButtonIndex;
    
    CGRect cropRect;
    
    UIImage* flashOnImage;
    UIImage* flashOffImage;
    
    UIView* captureAnimation;
    UIImageView* focusView;
    NSTimer* focusDelayTimer;
    int stepRotate;
    
    bool isActionBarEffectHidden;
    SystemSoundID captureSound;
}

@property (nonatomic, retain) UIView* loadingView;
@property (nonatomic, retain) UIView* changeSmoothValueView;

- (void) addActivityIndicatorWithText:(NSString*)text;
- (void) removeActivityIndicator;
- (void) addChangeSmoothValueView;
- (void) removeChangeSmoothValueView;
- (void) labelTap;
- (void) showHideChangeSmoothValueView;
- (void) brightnessSliderValueChange:(id)sender;
- (void) blurSizeSliderValueChange:(id)sender;
- (void) sharpenSliderValueChange:(id)sender;
- (void) resetSmoothSkinValue;
- (void) resetWhenInputImage;
- (void)inputImage:(UIImage*)image;
- (void)inputImage:(UIImage*)image isFirstTime:(bool)isFristTime;
- (void) flashButtonTouched;
- (void) switchCameraButtonTouched;
- (void) hideEffectBar:(bool)isHidden;
- (void) hideChangeSmoothValueView:(bool)isHidden;
- (void) effectButtonTouched;
- (void) updateEffectButtonBackground;
@end

@implementation CameraEffectViewController

@synthesize loadingView;
@synthesize changeSmoothValueView;
@synthesize inputImg;
@synthesize isEnableEffect;

- (id)init{
    if(self = [super init]){
        isHiddenEffectBar = true;
        actionBarUsing = 1;
        isCoverImage = NO;
        isEnableChangeSmoothValue = true;
        isEnableEffect = true;
        stepRotate = 0;
        
        NSString* captureSoundPath = [[NSBundle mainBundle] pathForResource:@"capture_sound" ofType:@"aiff"];
        NSURL* captureSoundUrl = [NSURL fileURLWithPath:captureSoundPath];
        AudioServicesCreateSystemSoundID((CFURLRef)captureSoundUrl, &captureSound);
    }
    return self;
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    NSLog(@"Receive memory warning");
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle


// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView
{
    [super loadView];
    
    int width = [UIScreen mainScreen].bounds.size.width;
    int height = [UIScreen mainScreen].bounds.size.height;
    
    activeSkinIcon = [[UIImage imageNamed:@"icon_skin.png"] retain];
    inactiveSkinIcon = [[UIImage imageNamed:@"icon_skin_dis.png" ] retain];
    activeBackgroundImage = [[UIImage imageNamed:@"active_background.png"] retain];
    
    
    
    UIImage* focusImage1 = [UIImage imageNamed:@"focus_point_1.png"];
    UIImage* focusImage2 = [UIImage imageNamed:@"focus_point_2.png"];
    NSArray* animateFocusImageArray = [NSArray arrayWithObjects:focusImage1, focusImage2, nil];
    
    focusView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, focusImage1.size.width, focusImage1.size.height)];
    focusView.hidden = true;
    focusView.animationDuration = 0.2;
    focusView.animationImages = animateFocusImageArray;
    [focusView startAnimating];
    
    [self addNewActionBarCapture];
    [self addNewActionBarMenu];
    [self addNewActionBarEffect];
    
    eaglView = [[[EAGLCameraView alloc] initWithFrame:CGRectMake(0, 0, width, height - actionBarMenu.frame.size.height)] autorelease];
    eaglView.animationInterval = 1.0/60.0;
    [eaglView setDelegate:self];
    
    if (inputImg) {
        [self inputImage:inputImg isFirstTime:true];
    }
    
    UIImage* effectButtonImage = [UIImage imageNamed:@"effect_arrow.png"];
    effectButton = [[UIButton alloc] initWithFrame:CGRectMake(250, actionBarEffectNew.frame.origin.y - effectButtonImage.size.height + 1, effectButtonImage.size.width, effectButtonImage.size.height)];
    [effectButton setImage:effectButtonImage forState:UIControlStateNormal];
    effectButton.backgroundColor = [UIColor clearColor];
    [effectButton addTarget:self action:@selector(effectButtonTouched) forControlEvents:UIControlEventTouchUpInside];
    
    isActionBarEffectHidden = true;
    
    [self.view addSubview:eaglView];
    [self.view addSubview:focusView];
    [self.view addSubview:effectButton];
    [self.view addSubview:actionBarEffectNew];
    [self.view addSubview:actionBarCapture];
    [self.view addSubview:actionBarMenu];
    
    
    actionBarMenu.alpha = 0;
    
    flashOnImage = [[UIImage imageNamed:@"btn_On.png"] retain];
    flashOffImage = [[UIImage imageNamed:@"btn_Off.png"] retain];
    
    if([eaglView hasFrontCamera]){
    
        flashButton = [[UIButton alloc] init];
        flashButton.frame = CGRectMake(20, 10, flashOnImage.size.width, flashOnImage.size.height);
        [flashButton addTarget:self action:@selector(flashButtonTouched) forControlEvents:UIControlEventTouchUpInside];
        flashButton.backgroundColor = [UIColor clearColor];
        [flashButton setBackgroundImage:flashOffImage forState:UIControlStateNormal];
        [self.view addSubview:flashButton];

    
        switchCameraButton = [[UIButton alloc] init];
        switchCameraButton.frame = CGRectMake(220, 10, 80, 40);
        [switchCameraButton addTarget:self action:@selector(switchCameraButtonTouched) forControlEvents:UIControlEventTouchUpInside];
        switchCameraButton.backgroundColor = [UIColor clearColor];
        [switchCameraButton setImage:[UIImage imageNamed:@"btn_FlipCamara.png"] forState:UIControlStateNormal];
        [self.view addSubview:switchCameraButton];
    }

}


- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

-(void)addNewActionBarEffect
{
    CGRect screenFrame = [[UIScreen mainScreen] applicationFrame];
    
    int iButtonWidth = 55;
    int iButtonHeight = 55;
    int topPadding = 4;
    
    UIImage *imageThumbBackground = [UIImage imageNamed: @"thumbnail-bar.png"];
    
    NSMutableArray* arrayImage = [[NSMutableArray alloc] init];
    for (int i = 0; i < 22; i++) {
        [arrayImage addObject:[UIImage imageNamed:@"Origin.png"]];
    }
    int iNumButton = arrayImage.count;
    
    NSMutableArray* arraySubName = [[NSMutableArray alloc] init];
    
    //Add thumbnail default
    [arraySubName addObject:@"0"];
    
    
    for (int i = 0; i < iNumButton - 1; i++) {
        NSString* strName = [NSString stringWithFormat:@"%d", (i+1)];
        [arraySubName addObject:strName];
    }
    
    //Add to bar item
    actionBarEffectNew = [[ImageMainMenuBarView alloc] initWithNumButton:iNumButton
                                                               arrayName:arraySubName
                                                        arrayImageNormal:arrayImage
                                                         arrayImageTouch:NULL
                                                              sizeButton:CGSizeMake(iButtonWidth, iButtonHeight) spaceButton:6
                                                               infoFrame:CGRectMake(0,screenFrame.size.height - actionBarMenu.frame.size.height, screenFrame.size.width, iButtonHeight + 2*topPadding)
                                                         imageBackground:imageThumbBackground
                                                                delegate:self
                                                            hasEffectOut:FALSE];
    
    
    [arrayImage removeAllObjects];
    UX_RELEASE_SAFELY(arrayImage);
    
    [arraySubName removeAllObjects];
    UX_RELEASE_SAFELY(arraySubName);
}

- (void)finishedAnimationWhenTouchButton:(NSInteger)iIndexSelected
{
    if(actionBarEffectNew.isHidden == false)
        [eaglView effect:iIndexSelected];
}

- (void)beginAnimationWhenTouchDown:(NSInteger)iIndexSelected
{
    
}

-(void)addNewActionBarMenu
{
    int iSubBarHeight = 46;
    
    CGRect screenFrame = [[UIScreen mainScreen] applicationFrame];
    UIImage* imageBackground = [UIImage imageNamed: @"bar1.png"];
    
    NSArray *imageNormal = nil;
    
    if(SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"5.0")){
        imageNormal = [[NSArray alloc] initWithObjects:
                       [UIImage imageNamed:@"icon_effect.png"],
//                       [UIImage imageNamed:@"icon_frame.png"],
                       [UIImage imageNamed:@"icon-xoaytrai.png"],
                       [UIImage imageNamed:@"icon-catvuong.png"],
                       activeSkinIcon,
                       nil];
    }
    else{
        imageNormal = [[NSArray alloc] initWithObjects:
                       [UIImage imageNamed:@"icon_effect.png"],
                       [UIImage imageNamed:@"icon-xoaytrai.png"],
                       [UIImage imageNamed:@"icon-catvuong.png"],
//                       [UIImage imageNamed:@"icon_frame.png"],
                       nil];
    }
    
    effectButtonIndex = 0;
    rotateButtonIndex = 1;
    cropButtonIndex = 2;
    smoothSkinButtonIndex = 3;
    
    int NumButtonSub = imageNormal.count;
    
    actionBarMenu = [[[ImageActionBarView alloc] initWithKindButton:NumButtonSub
                                                       spaceButton:0
                                                       imageNormal:imageNormal
                                                    imagesSelected:nil
                                                        sizeButton:CGSizeMake(W_BUTTON_MENU_BAR, H_BUTTON_MENU_BAR)
                                                             frame:CGRectMake(0,screenFrame.size.height - iSubBarHeight, screenFrame.size.width, iSubBarHeight)
                                                   imageBackground:imageBackground
                                                          delegate:self] autorelease];
    
    
    [imageNormal release];
    imageNormal = nil;
}

-(void)addNewActionBarCapture{
    int iSubBarHeight = 46;
    
    CGRect screenFrame = [[UIScreen mainScreen] applicationFrame];
    UIImage* imageBackground = [UIImage imageNamed: @"bar1.png"];
    
    NSArray *imageNormal = nil;
    
    imageNormal = [[NSArray alloc] initWithObjects:
//                   [UIImage imageNamed:@"icon_effect.png"],
                   [UIImage imageNamed:@"btn_capture.png"],
                   nil];
    
    int NumButtonSub = imageNormal.count;
    
    actionBarCapture = [[ImageActionBarView alloc] initWithKindButton:NumButtonSub
                                                       spaceButton:0
                                                       imageNormal:imageNormal
                                                    imagesSelected:nil
                                                        sizeButton:CGSizeMake(W_BUTTON_MENU_BAR, H_BUTTON_MENU_BAR)
                                                             frame:CGRectMake(0,screenFrame.size.height - iSubBarHeight, screenFrame.size.width, iSubBarHeight)
                                                   imageBackground:imageBackground
                                                          delegate:self];
    
//    CGRect currentFrame = [actionBarMenu frameOfButtonIndex:0];
//    [actionBarCapture setFrame:CGRectMake(actionBarCapture.frame.size.width/4 - currentFrame.size.width/2 + 10, currentFrame.origin.y, currentFrame.size.width, currentFrame.size.height) forButtonIndex:0];
//    [actionBarCapture setFrame:CGRectMake(actionBarCapture.frame.size.width/2 - currentFrame.size.width/2, currentFrame.origin.y, currentFrame.size.width, currentFrame.size.height) forButtonIndex:1];
    CGRect frameCaptureButton = [actionBarCapture frameOfButtonIndex:0];
    int captureButtonWidth = 90;
    int captureButtonHeight = 35;
    [actionBarCapture setFrame:CGRectMake(frameCaptureButton.origin.x + frameCaptureButton.size.width/2 - captureButtonWidth/2,
                                          (actionBarCapture.frame.size.height - captureButtonHeight)/2,
                                          captureButtonWidth, captureButtonHeight) forButtonIndex:0];
    UIButton* captureButton = [actionBarCapture buttonAtIndex:0];
    [captureButton setImage:[UIImage imageNamed:@"btn_capture_pressed.png"] forState:UIControlStateHighlighted];
    actionBarCapture.rightButton = nil;
    
    [imageNormal release];
    imageNormal = nil;
}

- (void)finishedActionSelected:(id)sender indexSelect:(int)iIndexSelected
{

    ImageActionBarView* actionBar = (ImageActionBarView*)sender;
    
    if(actionBar == actionBarCapture){                      
        if(iIndexSelected - 2 == 0){
//            actionBarEffectNew.hidden = !actionBarEffectNew.hidden;
//            isActionBarEffectHidden = !isActionBarEffectHidden;
//            [self hideEffectBar:isActionBarEffectHidden];
//            if(actionBarEffectNew.hidden == true)
//               [actionBarCapture updateBackgroundImageButtonAtIndex:iIndexSelected - 2 imageButton:nil];
//            else [actionBarCapture updateBackgroundImageButtonAtIndex:iIndexSelected - 2 imageButton:activeBackgroundImage];
//        }
//        else if(iIndexSelected - 2 == 1){               // capture
            [actionBarCapture buttonAtIndex:iIndexSelected - 2].userInteractionEnabled = false;
            [eaglView capture];
            focusView.hidden = true;
            stepRotate = 0;
            cropRect = CGRectMake(0, 0, 0, 0);
        }
    }
    else if(actionBar == actionBarMenu){
        if(isEnableEffect){
            if (iIndexSelected == kTagLeft) {
                [eaglView backToCamera];
//                actionBarCapture.hidden = false;
//                actionBarMenu.hidden = true;
//                flashButton.hidden = false;
//                switchCameraButton.hidden = false;
                [self hideChangeSmoothValueView:true];
//                [self hideEffectBar:actionBarEffectNew.hidden];
                
                // bar animation
//                actionBarMenu.alpha = 1;
//                actionBarCapture.alpha = 0;
                [UIView animateWithDuration:0.2 animations:^{
                    actionBarMenu.alpha = 0;
                    effectButton.alpha = 1;
                    flashButton.alpha = 1;
                    switchCameraButton.alpha = 1;
                } completion:^(BOOL finished) {
//                    actionBarCapture.hidden = false;
//                    actionBarMenu.hidden = true;
                }];
            }
            else if(iIndexSelected == kTagRight){
                
            }
            else if(iIndexSelected - 2 == rotateButtonIndex){                     // Rotate
                stepRotate++;
                [eaglView rotate];
            }
        
            else if(iIndexSelected - 2 == effectButtonIndex){                       // Effect
                [self effectButtonTouched];
                [self updateEffectButtonBackground];
                [self hideChangeSmoothValueView:true];

            }
            else if(iIndexSelected - 2 == cropButtonIndex){                     // Crop
                CropViewController* cropController = [[[CropViewController alloc] init] autorelease];
                cropController.delegate = self;
                cropController.inputImg = [eaglView getCaptureImage];
                cropController.stepRotate = stepRotate;
                cropController.cropRectInit = cropRect;
                [self presentModalViewController:cropController animated:YES];
            }
            else if(iIndexSelected  - 2 == smoothSkinButtonIndex){          // smooth skin
                if(SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"5.0")){
                    eaglView.isUseSmoothSkin = !eaglView.isUseSmoothSkin;
                    if(eaglView.isUseSmoothSkin == true){
                        [self hideEffectBar:true];
                        [self updateEffectButtonBackground];
                        [self addChangeSmoothValueView];
                        [actionBarMenu updateImageButtonAtIndex:iIndexSelected-2 imageButton:activeSkinIcon];
                        if(isProcessDefaultValue == false){
                            
                            [self resetSmoothSkinValue];
                            
                            [eaglView applySmoothSkinValue];
                            isProcessDefaultValue = true;
                        }
                    }
                    else{
                        [self removeChangeSmoothValueView];
                        [actionBarMenu updateImageButtonAtIndex:iIndexSelected-2 imageButton:inactiveSkinIcon];
                    }
                }
            }
            
            
        }
    }
    
}

- (void)effectButtonTouched{
    [self hideEffectBar:!isActionBarEffectHidden];
}

- (void)updateEffectButtonBackground{
    if(isActionBarEffectHidden){
        [actionBarMenu updateBackgroundImageButtonAtIndex:effectButtonIndex imageButton:nil];
    }
    else{
        [actionBarMenu updateBackgroundImageButtonAtIndex:effectButtonIndex imageButton:activeBackgroundImage];
    }
}

- (void) hideEffectBar:(bool)isHidden{
//    actionBarEffectNew.hidden = isHidden;
//    if(actionBarEffectNew.hidden){
//        [actionBarMenu updateBackgroundImageButtonAtIndex:effectButtonIndex imageButton:nil];
//        [actionBarCapture updateBackgroundImageButtonAtIndex:effectButtonIndex imageButton:nil];
//    }
//    else{
//        [actionBarMenu updateBackgroundImageButtonAtIndex:effectButtonIndex imageButton:activeBackgroundImage];
//        [actionBarCapture updateBackgroundImageButtonAtIndex:effectButtonIndex imageButton:activeBackgroundImage];
//    }
    
    if(isHidden == isActionBarEffectHidden) return;
    
    isActionBarEffectHidden = !isActionBarEffectHidden;
    int DISTANCE_MOVE = actionBarEffectNew.frame.size.height + 1;
    if(isHidden){
        [UIView animateWithDuration:0.3 animations:^{
            actionBarEffectNew.frame = CGRectMake(actionBarEffectNew.frame.origin.x, actionBarEffectNew.frame.origin.y + DISTANCE_MOVE, actionBarEffectNew.frame.size.width, actionBarEffectNew.frame.size.height);
            effectButton.frame = CGRectMake(effectButton.frame.origin.x, effectButton.frame.origin.y + DISTANCE_MOVE, effectButton.frame.size.width, effectButton.frame.size.height);
        }];
    }
    else{
        [UIView animateWithDuration:0.3 animations:^{
            actionBarEffectNew.frame = CGRectMake(actionBarEffectNew.frame.origin.x, actionBarEffectNew.frame.origin.y - DISTANCE_MOVE, actionBarEffectNew.frame.size.width, actionBarEffectNew.frame.size.height);
            effectButton.frame = CGRectMake(effectButton.frame.origin.x, effectButton.frame.origin.y - DISTANCE_MOVE, effectButton.frame.size.width, effectButton.frame.size.height);
        }];
    }
}

- (void) hideChangeSmoothValueView:(bool)isHidden{
    changeSmoothValueView.hidden = isHidden;
    isEnableChangeSmoothValue = !isHidden;
}

- (void)finishedActionSubItemSelected:(id)sender
                          indexSelect:(int)iIndexSelected
                   indexSubItemSelect:(int)iIndexSubItemSelect
{
    
}
- (void)slideValueChange:(NSInteger)newValue AtIndexSelect:(int)iIndexSelected
{
    
}

-(void)saveFile:(NSString*)filePath{
    [eaglView saveImageFinalTo:filePath];

}

-(void)dealloc{
    [eaglView stopAnimation];
    [actionBarEffectNew release];
    [flashOnImage release];
    [flashOffImage release];

    [actionBarMenu release];
    [actionBarCapture release];
    [actionBarEffectNew release];
    [loadingView release];
    [changeSmoothValueView release];
    [activeSkinIcon release];
    [inactiveSkinIcon release];
    [activeBackgroundImage release];
    [inputImg release];
    [actionBarCapture release];
    [focusView release];
    [switchCameraButton release];
    [flashButton release];
    AudioServicesDisposeSystemSoundID(captureSound);
    [super dealloc];
}

- (void)inputImage:(UIImage*)image{
    [eaglView inputImage:image];
    [self resetWhenInputImage];
    [eaglView startAnimation];
}

- (void)inputImage:(UIImage *)image isFirstTime:(bool)isFirstTime{
    [eaglView inputImage:image isFirstTime:isFirstTime];
    [self resetWhenInputImage];
    [eaglView startAnimation];
}

-(void)didFinishRotate:(id)sender{
}

- (void) addActivityIndicatorWithText:(NSString*)text{
    int activityWidth = 100;
    int activityHeight = 100;
    self.loadingView = [[[UIView alloc] initWithFrame:CGRectMake((self.view.frame.size.width - activityWidth)/2, (self.view.frame.size.height - activityHeight)/2, activityWidth, activityWidth)] autorelease];
    loadingView.layer.cornerRadius = 5;
    loadingView.backgroundColor = [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.7];
    
    int indicatorWidth = 30;
    UIActivityIndicatorView* activityIndicator = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
    activityIndicator.frame = CGRectMake((activityWidth - indicatorWidth)/2, (activityHeight - indicatorWidth)/2, indicatorWidth, indicatorWidth);
    [activityIndicator startAnimating];
    [loadingView addSubview:activityIndicator];
    
    int leftMargin = 5;
    UILabel* textLoading = [[UILabel alloc] initWithFrame:CGRectMake(leftMargin, activityIndicator.frame.origin.y + activityIndicator.frame.size.height + 15, loadingView.frame.size.width - 2*leftMargin, 10)];
    textLoading.backgroundColor = [UIColor clearColor];
    textLoading.textColor = [UIColor whiteColor];
    textLoading.text = text;
    textLoading.font = [UIFont systemFontOfSize:12];
    textLoading.textAlignment = UITextAlignmentCenter;
    [loadingView addSubview:textLoading];
    [textLoading release];
    
    [self.view addSubview:loadingView];
    
}

- (void) removeActivityIndicator{
    [loadingView removeFromSuperview];
}

- (void) addChangeSmoothValueView{
    int viewHeight = 90;
    
    if(changeSmoothValueView == nil){
        self.changeSmoothValueView = [[[UIView alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height - actionBarMenu.frame.size.height - viewHeight, self.view.frame.size.width, viewHeight)] autorelease];
        changeSmoothValueView.backgroundColor = [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.7];
        
        int leftMargin = 10;
        int topMargin = 5;
        int labelWidth = 70;
        int labelHeight = 20;
        int sliderLeftMargin = leftMargin + labelWidth + 10;
        int sliderWidth = self.view.frame.size.width - sliderLeftMargin - 10;
        int numRow = 3;
        
        UILabel* brightnessLabel = [[UILabel alloc] initWithFrame:CGRectMake(leftMargin, topMargin, labelWidth, labelHeight)];
        brightnessLabel.text = @"Độ sáng da";
        brightnessLabel.backgroundColor = [UIColor clearColor];
        brightnessLabel.textColor = [UIColor whiteColor];
        brightnessLabel.font = [UIFont boldSystemFontOfSize:12];
        [changeSmoothValueView addSubview:brightnessLabel];
        [brightnessLabel release];
        
        brightnessSlider = [[UISlider alloc] initWithFrame:CGRectMake(sliderLeftMargin, topMargin, sliderWidth, labelHeight)];
        [brightnessSlider addTarget:self action:@selector(brightnessSliderValueChange:) forControlEvents:UIControlEventTouchUpInside];
        [brightnessSlider addTarget:self action:@selector(brightnessSliderValueChange:) forControlEvents:UIControlEventTouchUpOutside];
        brightnessSlider.minimumValue = 0.0;
        brightnessSlider.maximumValue = 0.3;
        [changeSmoothValueView addSubview:brightnessSlider];
        [brightnessSlider release];
        
        UILabel* smoothLabel = [[UILabel alloc] initWithFrame:CGRectMake(leftMargin, topMargin + viewHeight/numRow, labelWidth, labelHeight)];
        smoothLabel.text = @"Độ mịn da";
        smoothLabel.backgroundColor = [UIColor clearColor];
        smoothLabel.textColor = [UIColor whiteColor];
        smoothLabel.font = [UIFont boldSystemFontOfSize:12];
        [changeSmoothValueView addSubview:smoothLabel];
        [smoothLabel release];
        
        smoothSlider = [[UISlider alloc] initWithFrame:CGRectMake(sliderLeftMargin, topMargin + viewHeight/numRow, sliderWidth, labelHeight)];
        [smoothSlider addTarget:self action:@selector(blurSizeSliderValueChange:) forControlEvents:UIControlEventTouchUpInside];
        [smoothSlider addTarget:self action:@selector(blurSizeSliderValueChange:) forControlEvents:UIControlEventTouchUpOutside];
        smoothSlider.minimumValue = 0.0;
        smoothSlider.maximumValue = 3.0;
        [changeSmoothValueView addSubview:smoothSlider];
        [smoothSlider release];
        
        UILabel* sharpenLabel = [[UILabel alloc] initWithFrame:CGRectMake(leftMargin, topMargin + 2*viewHeight/numRow, labelWidth, labelHeight)];
        sharpenLabel.text = @"Độ sắc nét";
        sharpenLabel.backgroundColor = [UIColor clearColor];
        sharpenLabel.textColor = [UIColor whiteColor];
        sharpenLabel.font = [UIFont boldSystemFontOfSize:12];
        [changeSmoothValueView addSubview:sharpenLabel];
        [sharpenLabel release];
        
        sharpenSlider = [[UISlider alloc] initWithFrame:CGRectMake(sliderLeftMargin, topMargin + 2*viewHeight/3, sliderWidth, labelHeight)];
        [sharpenSlider addTarget:self action:@selector(sharpenSliderValueChange:) forControlEvents:UIControlEventTouchUpInside];
        [sharpenSlider addTarget:self action:@selector(sharpenSliderValueChange:) forControlEvents:UIControlEventTouchUpOutside];
        sharpenSlider.minimumValue = 0.0;
        sharpenSlider.maximumValue = 3.0;
        [changeSmoothValueView addSubview:sharpenSlider];
        [sharpenSlider release];
        
        [self resetSmoothSkinValue];
    }

    isEnableChangeSmoothValue = true;
    [self showHideChangeSmoothValueView];
    [self.view addSubview:changeSmoothValueView];
}

- (void) removeChangeSmoothValueView{
    [changeSmoothValueView removeFromSuperview];
}

- (void)shouldFaceDetection:(id)sender{
    NSThread* thread = [[NSThread alloc] initWithTarget:self selector:@selector(addActivityIndicatorWithText:) object:@"Làm mịn da"];
    [thread start];
    [thread release];
}

- (void)didFaceDetection:(id)sender{
    [self removeActivityIndicator];
}

- (void)eaglViewTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    if(SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"5.0") == true)
        if(isActionBarEffectHidden && actionBarMenu.alpha == 1)
            [self showHideChangeSmoothValueView];
    
    if(actionBarMenu.alpha == 0){
    
        UITouch* touch = [[touches allObjects] objectAtIndex:0];
        
        // add focus
        CGPoint touchPoint = [touch locationInView:self.view];
        focusView.frame = CGRectMake(touchPoint.x - focusView.frame.size.width/2, touchPoint.y - focusView.frame.size.height/2, focusView.frame.size.width, focusView.frame.size.height);
        focusView.hidden = false;
        [focusDelayTimer invalidate];
        [focusDelayTimer release];
        focusDelayTimer = [[NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(removeFocusView) userInfo:nil repeats:NO] retain];
    }
}

- (void) removeFocusView{
    focusView.hidden = true;
}

- (void) labelTap{
    if(SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"5.0") == true)
        [self showHideChangeSmoothValueView];
}

- (void) showHideChangeSmoothValueView{
    if(eaglView.isUseSmoothSkin == false) return;
    if(isEnableChangeSmoothValue == true){
        changeSmoothValueView.hidden = false;
        isEnableChangeSmoothValue = false;
    }
    else{
        changeSmoothValueView.hidden = true;
        isEnableChangeSmoothValue = true;
    }
}

- (void) brightnessSliderValueChange:(id)sender{
    [eaglView setStandardBrightness:brightnessSlider.value];
    [eaglView applySmoothSkinValue];
}

- (void) blurSizeSliderValueChange:(id)sender{
    [eaglView setBlurSize:smoothSlider.value];
    [eaglView applySmoothSkinValue];
}

- (void) sharpenSliderValueChange:(id)sender{
    [eaglView setSharpness:sharpenSlider.value];
    [eaglView applySmoothSkinValue];
}

- (void) resetSmoothSkinValue{
    smoothSlider.value = [eaglView blurSizeOfBeautifulFilter];
    brightnessSlider.value = STANDARD_BRIGHTNESS;
    sharpenSlider.value = smoothSlider.value;
    [eaglView setBlurSize:smoothSlider.value];
    [eaglView setStandardBrightness:brightnessSlider.value];
    [eaglView setSharpness:sharpenSlider.value];
}

- (void) resetWhenInputImage{
    isEnableChangeSmoothValue = false;
    changeSmoothValueView.hidden = true;
    isProcessDefaultValue = false;
}

- (void)didCropResultImage:(UIImage *)image cropRect:(CGRect)rect sender:(CropViewController *)sender{
    
    if(image){
        [self inputImage:image isFirstTime:false];
        stepRotate = 0;
        cropRect = rect;
    }
}

- (void) flashButtonTouched{
    eaglView.isFlashOn = !eaglView.isFlashOn;
    if(eaglView.isFlashOn)
        [flashButton setBackgroundImage:flashOnImage forState:UIControlStateNormal];
    else [flashButton setBackgroundImage:flashOffImage forState:UIControlStateNormal];
}

- (void) switchCameraButtonTouched{
    [eaglView rotateCamera];
}

- (BOOL)isFrontFacingCameraPresent;
{
	NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
	
	for (AVCaptureDevice *device in devices)
	{
		if ([device position] == AVCaptureDevicePositionFront)
			return YES;
	}
	
	return NO;
}

-(void)didCaptureImage{
    
    [actionBarCapture buttonAtIndex:CAPTURE_INDEX].userInteractionEnabled = true;
    
    AudioServicesPlaySystemSound(captureSound);
    
    // capture animation
    int animationSizeInit = 10;
    if(captureAnimation == nil){
        captureAnimation = [[UIView alloc] initWithFrame:CGRectMake((self.view.frame.size.width - animationSizeInit)/2, (self.view.frame.size.height - animationSizeInit)/2, animationSizeInit, animationSizeInit)];
    }
    
    captureAnimation.backgroundColor = [UIColor whiteColor];
    captureAnimation.alpha = 0;
    [self.view addSubview:captureAnimation];
    
    [UIView animateWithDuration:0.1 animations:^{
        captureAnimation.alpha = 1;
        captureAnimation.frame = eaglView.frame;
    } completion:^(BOOL finished) {
        [UIView animateWithDuration:0.05 animations:^{
            captureAnimation.backgroundColor = [UIColor clearColor];
        } completion:^(BOOL finished) {
            [captureAnimation removeFromSuperview];
        }];
    }];
    
    // bar animation
    [UIView animateWithDuration:0.2 animations:^{
        actionBarMenu.alpha = 1;
        effectButton.alpha = 0;
        switchCameraButton.alpha = 0;
        flashButton.alpha = 0;
    } completion:^(BOOL finished) {
    }];
}
@end
